package cn.starrysky.hrm.service.impl;

import cn.starrysky.hrm.contants.CourseServiceContants;
import cn.starrysky.hrm.coursevo.CrumbsVo;
import cn.starrysky.hrm.domain.CourseType;
import cn.starrysky.hrm.mapper.CourseTypeMapper;
import cn.starrysky.hrm.service.ICourseTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author starrysky
 * @since 2021-03-06
 */
public class CourseTypeServiceImpl_cache extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Override
    @Cacheable(cacheNames = CourseServiceContants.COURSE_TYPE_TREE_DATA,key = "'ALL'")
    public List<CourseType> treeData() {
        return treeDataloop();
    }

    @Override
    public List<CrumbsVo> crumbs(Long id) {
        return null;
    }

    //添加删除更新之后都要同步缓存 删除缓存
    @Override
    @CacheEvict(cacheNames = CourseServiceContants.COURSE_TYPE_TREE_DATA,key = "'ALL'")
    public boolean insert(CourseType entity) {
        //删除缓存
        redisTemplate.delete(CourseServiceContants.COURSE_TYPE_TREE_DATA);
        return super.insert(entity);
    }

    @Override
    @CacheEvict(cacheNames = CourseServiceContants.COURSE_TYPE_TREE_DATA,key = "'ALL'")
    public boolean deleteById(Serializable id) {
        //删除缓存
        return super.deleteById(id);
    }

    @Override
    @CacheEvict(cacheNames = CourseServiceContants.COURSE_TYPE_TREE_DATA,key = "'ALL'")
    public boolean updateById(CourseType entity) {
        //删除缓存
        return super.updateById(entity);
    }

    private List<CourseType> treeDataloop() {
        System.out.println("========查询的数据库========");
        //准备一个list返回
        List<CourseType> result = new ArrayList<>();
        //先查出所有的类型
        List<CourseType> courseTypes = courseTypeMapper.selectList(null);
        Map<Long,Object> map=new HashMap();
        //遍历集合，将id作为key绑定本身对象
        courseTypes.forEach(mType->{
            map.put(mType.getId(), mType);
        });
        //遍历
        courseTypes.forEach(courseType -> {
            //如果是第一级
            if(courseType.getPid()==0){
                result.add(courseType);
            }else { //如果是第二级 或者后面几级先找他们的父节然后加在其子级
                //更具pid获取父级对象
                CourseType parent =(CourseType) map.get(courseType.getPid());
                //父级children 作为儿子放进去
                parent.getChildren().add(courseType);
            }
        });
        return result;
    }

}
